package com.zeros.myself.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;

/**
 * 在当前activity的onCreate中，调用方法StatusBarCompat.compat就可以了 on 2017/12/8.
 * //第二个参数是想要设置的颜色
 * StatusBarCompat.compat(this, Color.RED);
 */

public class StatusBarCompat {

    private static final int INVALID_VAL = -1;
    private static final int COLOR_DEFAULT = Color.parseColor("#20000000");

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void compat(Activity activity, int statusColor) {

        //当前手机版本为5.0及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (statusColor != INVALID_VAL) {
                activity.getWindow().setStatusBarColor(statusColor);
            }
            return;
        }

        //当前手机版本为4.4
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            int color = COLOR_DEFAULT;
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            if (statusColor != INVALID_VAL) {
                color = statusColor;
            }
            View statusBarView = new View(activity);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(activity));
            statusBarView.setBackgroundColor(color);
            contentView.addView(statusBarView, lp);
        }
    }

    public static void compat(Activity activity) {
        compat(activity, INVALID_VAL);
    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
	
	
	//DIP：Density Independent Pixel，直译为密度无关的像素。布局文件中使用的dp/dip就是它
    //官方推荐使用dp是因为它会根据你设备的密度算出对应的像素。公式为：pixel = dip*density
    //private int convertDpToPixel(int dp) {
    //    DisplayMetrics metrics = getResources().getDisplayMetrics();
    //    return (int) (dp * metrics.density);
    //}

    //private int convertPixelToDp(int pixel) {
    //    DisplayMetrics metrics = getResources().getDisplayMetrics();
    //    return (int) (pixel / metrics.density);
    //}

	//public static int px2dp(Context context, float pxValue) {
    //    float scale = context.getResources().getDisplayMetrics().density;
    //    return (int) (pxValue / scale + 0.5f);
    //}

}
